/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.security.token.store;

import org.tianyun.cloud.data.redis.factory.ObjectRedisTemplate;
import org.tianyun.cloud.security.token.common.AccessToken;

import java.security.Principal;

/**
 * redis token store
 *
 * @auther ebert_chan
 */
public class RedisTokenStore implements TokenStore {

    private static final String KEY_ACCESS_TOKEN = "security:token:store:{0}";

    private ObjectRedisTemplate redisTemplate;

    public RedisTokenStore(ObjectRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /*
     * @see org.tianyun.cloud.security.token.store.TokenStore#getAccessToken(java.security.Principal)
     */
    @Override
    public AccessToken getAccessToken(Principal principal) {
        String key = redisTemplate.covertKey(KEY_ACCESS_TOKEN, principal.getName());
        byte[] bytes = redisTemplate.get(key, byte[].class);
        AccessToken accessToken = redisTemplate.deserializeForJdkSerializer(bytes);
        if (accessToken != null && accessToken.isExpired()) {
            redisTemplate.delete(key);
            accessToken = null;
        }
        return accessToken;
    }

    /*
     * @see org.tianyun.cloud.security.token.store.TokenStore#storeAccessToken(java.security.Principal,
     * org.tianyun.cloud.security.token.common.AccessToken)
     */
    @Override
    public void storeAccessToken(Principal principal, AccessToken accessToken) {
        String key = redisTemplate.covertKey(KEY_ACCESS_TOKEN, principal.getName());
        byte[] bytes = redisTemplate.serializeForJdkSerializer(accessToken);
        if (accessToken.getExpiresIn() != null && accessToken.getExpiresIn() > 0) {
            redisTemplate.set(key, bytes, accessToken.getExpiresIn());
        } else {
            redisTemplate.set(key, bytes);
        }
    }

    /*
     * @see org.tianyun.cloud.security.token.store.TokenStore#removeAccessToken(java.security.Principal)
     */
    @Override
    public void removeAccessToken(Principal principal) {
        String key = redisTemplate.covertKey(KEY_ACCESS_TOKEN, principal.getName());
        redisTemplate.delete(key);
    }

}
